<?php

require_once __DIR__ . '/../vendor/autoload.php';

use JingdongApi\JingdongApiSDK;
use JingdongApi\Models\OrderData;
use JingdongApi\Models\MerchantInfo;

// 配置SDK
$config = [
    'app_key' => 'your_app_key',
    'app_secret' => 'your_app_secret',
    'merchant_no' => 'your_merchant_no',
    'sandbox_mode' => true, // 测试环境
    'enable_log' => true
];

$sdk = new JingdongApiSDK($config);

// 设置日志回调（可选）
$sdk->setLogger(function($level, $message, $context) {
    echo sprintf("[%s] %s %s\n", 
        strtoupper($level), 
        $message, 
        !empty($context) ? json_encode($context, JSON_UNESCAPED_UNICODE) : ''
    );
});

echo "=== 京东配送API SDK 示例 ===\n\n";

// 1. 测试连接
echo "1. 测试API连接...\n";
$result = $sdk->testConnection();
if ($result->success) {
    echo "✓ API连接正常\n";
} else {
    echo "✗ API连接失败: " . $result->message . "\n";
}
echo "\n";

// 2. 申请成为配送商（示例）
echo "2. 申请成为配送商...\n";
$merchantInfo = new MerchantInfo([
    'merchant_name' => '测试商户',
    'merchant_phone' => '13800138000',
    'merchant_address' => '北京市朝阳区测试地址',
    'business_license' => '91110000000000000X',
    'contact_person' => '张三',
    'contact_phone' => '13800138001',
    'merchant_type' => '1'
]);

try {
    $result = $sdk->applyMerchant($merchantInfo);
    if ($result->success) {
        echo "✓ 申请提交成功\n";
        echo "申请ID: " . ($result->data['apply_id'] ?? 'N/A') . "\n";
    } else {
        echo "✗ 申请失败: " . $result->message . "\n";
    }
} catch (Exception $e) {
    echo "✗ 申请异常: " . $e->getMessage() . "\n";
}
echo "\n";

// 3. 查询配送商状态
echo "3. 查询配送商状态...\n";
$result = $sdk->queryMerchantStatus();
if ($result->success) {
    echo "✓ 查询成功\n";
    echo "状态: " . ($result->data['status'] ?? 'N/A') . "\n";
} else {
    echo "✗ 查询失败: " . $result->message . "\n";
}
echo "\n";

// 4. 预下单（获取运费）
echo "4. 预下单获取运费...\n";
$preOrderData = [
    'cargo_type' => '1',
    'cargo_weight' => 1000, // 1kg
    'cargo_num' => '1',
    'cargo_price' => '100.00',
    'pickup_info' => [
        'address' => '北京市朝阳区发货地址',
        'lng' => 116.397470,
        'lat' => 39.908860
    ],
    'delivery_info' => [
        'address' => '北京市海淀区收货地址',
        'lng' => 116.307490,
        'lat' => 39.981730
    ],
    'expected_pickup_time' => time() + 3600, // 1小时后取货
    'expected_delivery_time' => time() + 7200 // 2小时后送达
];

$result = $sdk->preOrder($preOrderData);
if ($result->success) {
    echo "✓ 询价成功\n";
    echo "配送费: " . ($result->data['delivery_fee'] ?? 'N/A') . " 元\n";
} else {
    echo "✗ 询价失败: " . $result->message . "\n";
}
echo "\n";

// 5. 创建配送订单
echo "5. 创建配送订单...\n";
$orderData = new OrderData([
    'orderId' => 'TEST_ORDER_' . time(),
    'tradeOrderSource' => 1,
    'serviceCode' => 'STANDARD',
    'recipientName' => '李四',
    'recipientPhone' => '13900139000',
    'recipientAddress' => '北京市海淀区收货地址123号',
    'recipientLng' => 116.307490,
    'recipientLat' => 39.981730,
    'prebook' => 0,
    'totalWeight' => 1, // 1kg
    'senderLng' => 116.397470,
    'senderLat' => 39.908860,
    'senderName' => '王五',
    'senderPhone' => '13800138000',
    'senderAddress' => '北京市朝阳区发货地址456号',
    'operatorName' => '王五',
    'extInfo' => [
        'remark' => '测试订单，请小心配送'
    ],
    'orderRemark' => '测试订单备注',
    'shopRemark' => '商户备注信息'
]);

try {
    $result = $sdk->createOrder($orderData);
    if ($result->success) {
        echo "✓ 订单创建成功\n";
        echo "京东订单号: " . ($result->data['jd_order_id'] ?? 'N/A') . "\n";
        $jdOrderId = $result->data['jd_order_id'] ?? null;
    } else {
        echo "✗ 订单创建失败: " . $result->message . "\n";
        $jdOrderId = null;
    }
} catch (Exception $e) {
    echo "✗ 订单创建异常: " . $e->getMessage() . "\n";
    $jdOrderId = null;
}
echo "\n";

// 6. 查询订单状态
if ($jdOrderId) {
    echo "6. 查询订单状态...\n";
    $result = $sdk->queryOrder($orderData->orderId, $jdOrderId);
    if ($result->success) {
        echo "✓ 查询成功\n";
        echo "订单状态: " . ($result->data['status'] ?? 'N/A') . "\n";
        echo "骑手信息: " . ($result->data['rider_name'] ?? 'N/A') . "\n";
    } else {
        echo "✗ 查询失败: " . $result->message . "\n";
    }
    echo "\n";
    
    // 7. 查询骑手位置
    echo "7. 查询骑手位置...\n";
    $result = $sdk->queryRiderLocation($orderData->orderId);
    if ($result->success) {
        echo "✓ 查询成功\n";
        echo "骑手位置: " . ($result->data['rider_lng'] ?? 'N/A') . ", " . ($result->data['rider_lat'] ?? 'N/A') . "\n";
    } else {
        echo "✗ 查询失败: " . $result->message . "\n";
    }
    echo "\n";
}

// 8. 查询可配送范围
echo "8. 查询可配送范围...\n";
$result = $sdk->queryServiceArea('116.397470', '39.908860');
if ($result->success) {
    echo "✓ 查询成功\n";
    echo "可配送: " . ($result->data['deliverable'] ? '是' : '否') . "\n";
} else {
    echo "✗ 查询失败: " . $result->message . "\n";
}
echo "\n";

// 9. 查询历史订单列表
echo "9. 查询历史订单列表...\n";
$condition = [
    'page_size' => 10,
    'page_no' => 1,
    'start_time' => date('Y-m-d 00:00:00'),
    'end_time' => date('Y-m-d 23:59:59')
];

$result = $sdk->queryOrderList($condition);
if ($result->success) {
    echo "✓ 查询成功\n";
    echo "订单数量: " . count($result->data['orders'] ?? []) . "\n";
} else {
    echo "✗ 查询失败: " . $result->message . "\n";
}
echo "\n";

// 10. 验证回调签名（示例）
echo "10. 验证回调签名...\n";
$callbackData = [
    'out_order_id' => 'TEST_ORDER_123456',
    'jd_order_id' => 'JD_123456789',
    'order_status' => '20',
    'rider_name' => '配送员张三',
    'rider_phone' => '13700137000'
];

// 生成签名进行验证
$testSignature = 'test_signature_here';
$isValid = $sdk->verifyCallback($callbackData, $testSignature);
echo ($isValid ? "✓ 签名验证通过" : "✗ 签名验证失败") . "\n";
echo "\n";

echo "=== 示例执行完成 ===\n";
